﻿
Imports std
Imports xmlctrl
Imports xhtmlctrl
Imports webctrl

Public MustInherit Class recent(Of T)
    Inherits cacheControlProcessor

    Private _s As fllist(Of T) = Nothing
    Private timer3Index As Guid = Nothing

    Private Function s() As fllist(Of T)
        assert(Not _s Is Nothing, "_s is not initialized.")
        Return _s
    End Function

    Protected Overrides Function normalRetiredTicks() As Int64
        Return secondsToTicks(10)
    End Function

    Protected Overridable Function writebackIntervalMS() As Int64
        Return secondsToMilliseconds(30)
    End Function

    Public Overloads Sub initial(ByVal count As Int64)
        _s = New fllist(Of T)(count)
        read()
        timer3Index = timer3.addcall(AddressOf timer3callback, writebackIntervalMS())
    End Sub

    Public Sub insert(ByVal v As T)
        SyncLock s()
            Dim it As fllist(Of T).iterator = Nothing
            it = s().find(v)
            If it <> s().end() Then
                s().erase(it)
            End If
            s().push_back(v)
        End SyncLock
        clearcache()
    End Sub

    Public Function output() As vector(Of T)
        Dim v As vector(Of T) = Nothing
        SyncLock s()
            v = list2vector(s())
        End SyncLock

        Return v
    End Function

    Private Sub timer3callback()
        SyncLock s()
            write(output())
        End SyncLock
    End Sub

    Protected MustOverride Sub write(ByVal l As vector(Of T))
    Protected MustOverride Sub read()

    Protected MustOverride Overloads Function processImpl(ByRef control As xmlcontrol, _
                                                          ByVal l As vector(Of T)) As Boolean

    Protected NotOverridable Overrides Function processImpl(ByVal context As httpContext, _
                                                            ByRef control As xmlcontrol) As Boolean
        Return processImpl(control, output())
    End Function

    Protected Overrides Sub closeImpl()
        timer3.removecall(timer3Index)
        timer3callback()
        MyBase.closeImpl()
    End Sub
End Class
